<template>
  <!-- 七牛 腾讯 暂时没有用到 -->
  <div style="position:relative">
    <template v-if="showDom">
      <a @click="upload">{{ $t('upload') }}</a>
    </template>
    <a-progress
      class="progressCss"
      :class="!showDom?'progress':''"
      v-if="loadData.loading"
      :percent="percent"
    />
    <input
      ref="upload"
      @change="fileChange"
      type="file"
      v-show="show"
      :accept="accept?accept:'*'"
    />
  </div>
</template>

<script>
import { uploadToQiniu } from '@/utils/upload'
import SparkMD5 from 'spark-md5'
const COS = require('cos-js-sdk-v5')
// 上传文件组件
export default {
  name: 'KwUploader',
  props: {
    loadData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 是否dom样式改变
    showDom: {
      type: Boolean,
      default: true
    },
    accept: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  computed: {
    acceptStr () {
      return this.accept.toString()
    }
  },
  data () {
    return {
      fileName: '',
      fileSize: 0,
      show: false,
      percent: 0,
      message: '请等待...',
      md5: undefined,
      putExtra: {
        fname: undefined,
        params: {},
        mimeType: null
      },
      apkInfo: {}
    }
  },
  methods: {
    next (res) {
      if (process.env.VUE_APP_CDNPosition === 'TENCENT') {
        // 客户要求
        this.percent = parseInt(res.percent * 100) // 腾讯云的进度条
      } else if (process.env.VUE_APP_CDNPosition === 'QINIU') {
        this.percent = parseInt(res.total.percent, 10) //  七牛云的进度条配置
      }
    },
    error (err) {
      this.$set(this.loadData, 'loading', false)
      this.message = err || err.message || '上传失败'
    },
    complete (res) {
      this.$set(this.loadData, 'loading', false)
      if (process.env.VUE_APP_CDNPosition === 'TENCENT') {
        // 腾讯云
        this.$set(this.loadData, 'url', `${process.env.VUE_APP_CDNDomain}/${res.fname}`)
        this.$set(this.loadData, 'upType', '1')
        this.$set(this.loadData, 'md5', this.md5)
        this.$set(this.loadData, 'size', this.fileSize)
        this.$set(this.loadData, 'packageName', this.fileName)
      } else if (process.env.VUE_APP_CDNPosition === 'QINIU') {
        // 七牛云
        this.$set(this.loadData, 'url', `${process.env.VUE_APP_CDNDomain}/${res.key}`)
        this.$set(this.loadData, 'upType', '2')
        this.$set(this.loadData, 'md5', this.md5)
        this.$set(this.loadData, 'size', this.fileSize)
        this.$set(this.loadData, 'packageName', this.fileName)
      }
    },
    fileMd5 (md5) {
      this.md5 = md5
    },
    fileChange (event) {
      const _this = this
      _this.percent = 0
      const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      const file = event.target.files[0]
      const length1 = file.name.lastIndexOf('.') // 取到文件名开始到最后一个点的长度
      const length = file.name.length // 文件名总长度
      const fileFormat = file.name.substring(length1, length) // 截取文件格式
      //   进行格式判断
      if (_this.accept.length > 0) {
        // eslint-disable-next-line no-unused-vars
        const tag = _this.accept.findIndex((value, index, arr) => {
          return value === fileFormat
        })
        if (tag === -1) {
          this.$message.warning(`${_this.$t('pleaseUpload')} ${_this.acceptStr} ${_this.$t('typesOf')}`)
          return
        }
      }
      const chunkSize = 30 * 1024 * 1024 // Read in chunks of 20MB
      const chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0
      const spark = new SparkMD5.ArrayBuffer()
      const fileReader = new FileReader()
      _this.$set(_this.loadData, 'loading', true)
      fileReader.onload = function (e) {
        // console.log('read chunk nr', currentChunk + 1, 'of', chunks)
        spark.append(e.target.result) // Append array buffer
        currentChunk = currentChunk + 1
        if (currentChunk < chunks) {
          loadNext()
        } else {
          _this.fileMd5(spark.end())
          const timestamp1 = Date.parse(new Date())
          if (process.env.VUE_APP_CDNPosition === 'TENCENT') {
            // 腾讯云
            const cos = new COS({
              SecretId: 'AKIDKUTHzQqqocGj1Drra7Xmy2H1dCZosZvA', // 密钥id
              SecretKey: 'JvNDuYAF9rW1TmvvjmnfMtFTW6ZwAPXW' // 密钥的key
            })
            let BucketName = ''
            if (process.env.NODE_ENV === 'production') {
              BucketName = 'ota-download-1256532032'
            } else {
              BucketName = 'ota-test-download-1256532032'
            }
            cos.putObject(
              {
                Bucket: BucketName, // 桶名-APPID  必须
                Region: 'ap-chengdu', // 区域 必须
                Key: `${timestamp1}-${_this.fileName}`, // 文件名必须
                Body: event.target.files[0], // 上传文件对象
                onProgress: function (progressData) {
                  _this.next(progressData)
                }
              },
              function (err, data) {
                if (data && data.statusCode === 200) {
                  _this.$set(data, 'fname', `${timestamp1}-${_this.fileName}`)
                  _this.complete(data)
                } else {
                  console.log(err, data) // 上传失败的返回值
                }
              }
            )
          } else if (process.env.VUE_APP_CDNPosition === 'QINIU') {
            // 七牛云上传
            _this.putExtra.fname = `${timestamp1}-${_this.fileName}`
            uploadToQiniu(
              event.target.files[0],
              `${timestamp1}-${_this.fileName}`,
              { next: _this.next, error: _this.error, complete: _this.complete },
              _this.putExtra
            )
          }
        }
      }

      fileReader.onerror = function () {
        _this.$set(_this.loadData, 'loading', false)
      }

      function loadNext () {
        const start = currentChunk * chunkSize
        const end = start + chunkSize >= file.size ? file.size : start + chunkSize

        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
      }

      loadNext()
    },
    upload () {
      this.$refs.upload.click()
    }
  }
}
</script>

<style lang='less' scoped>
.progressCss {
  position: absolute;
  bottom: -15px;
  left: 0;
  width: 100%;
  &.progress {
    bottom: -20px;
  }
}
</style>
